/**
 * 
 */
package com.owen.he.jee.dao.impl.ibatis;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ibatis.sqlmap.engine.execution.SqlExecutor;
import com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback;
import com.ibatis.sqlmap.engine.scope.StatementScope;

/**
 * 说明:在executeQuery执行前组装sql，
 * 然后将其传给executeQuery，<p>
 * 并告诉handleResults我们不需要逻辑分页<p>
 * @author meteor
 * 2007-3-14
 */
public class LimitSqlExecutor extends SqlExecutor {

    private static final Log logger = LogFactory.getLog(LimitSqlExecutor.class);
    
    /**
     * 数据库方言接口
     */
    private Dialect dialect;
    
    /**
     * 是否有限制
     */
    private boolean enableLimit = true;

    @Override
    public void executeQuery(StatementScope request, Connection conn, String sql,
            Object[] parameters, int skipResults, int maxResults,
            RowHandlerCallback callback) throws SQLException {
        if ((skipResults != NO_SKIPPED_RESULTS || maxResults != NO_MAXIMUM_RESULTS)
                && supportsLimit()) {
            sql = dialect.getLimitString(sql, skipResults, maxResults);
//            if(logger.isDebugEnabled()){
//                logger.debug(sql);
//            }
//            告诉handleResults不分页（我们组装的sql已经使查询结果是分页后的结果了）
            skipResults = NO_SKIPPED_RESULTS;
            maxResults = NO_MAXIMUM_RESULTS;            
        }
//        logger.info(sql);
        super.executeQuery(request, conn, sql, parameters, skipResults,
                maxResults, callback);
    }
    
    /**
     * 
     * @return
     */
    public boolean supportsLimit() {
        if (enableLimit && dialect != null) {
            return dialect.supportsLimit();
        }
        return false;
    }

    public Dialect getDialect() {
        return dialect;
    }

    public void setDialect(Dialect dialect) {
        this.dialect = dialect;
    }

    public boolean isEnableLimit() {
        return enableLimit;
    }

    public void setEnableLimit(boolean enableLimit) {
        this.enableLimit = enableLimit;
    }
}

